#include "../StdAfx.h"
#include "ArchiveItemMap.h"

using namespace SevenZip;

SevenZip::CSevenZipArchiveItemMap::CSevenZipArchiveItemMap(CONST CComPtr<IInArchive> & InArchive)
	: _InArchive(InArchive)
	, _Root(NULL)
{
}

STDMETHODIMP SevenZip::CSevenZipArchiveItemMap::AddItem(UINT32 ItemIndex)
{
	HRESULT hr;

	CStringW Path;
	CSevenZipArchiveItem * Item = new CSevenZipArchiveItem(_InArchive, ItemIndex);
	CSevenZipArchiveItem * Parent = NULL;

	if (SUCCEEDED(hr = Item->GetPath(Path)))
	{
		if (SUCCEEDED(hr = FindItemByPath(Path, Item)))
		{
			Item->SetIndex(ItemIndex);

			if (SUCCEEDED(hr = GetParentItem(Item, Parent)))
			{
				Parent->AddChildItem(Item);
			}
		}
	}

	return hr;
}

STDMETHODIMP SevenZip::CSevenZipArchiveItemMap::FindItemByPath(CONST CStringW & Path, CSevenZipArchiveItem * & Item)
{
	CSevenZipArchiveItem * Existing = NULL;
	
	if (_Map.Lookup(Path, Existing))
	{
		delete Item;
		Item = Existing;
	}
	else
	{
		_Map.SetAt(Path, Item);
	}

	return S_OK;
}

STDMETHODIMP SevenZip::CSevenZipArchiveItemMap::GetParentItem(CSevenZipArchiveItem * Item, CSevenZipArchiveItem * & Parent)
{
	CStringW ParentPath;
	HRESULT hr;
	
	if (SUCCEEDED(hr = Item->GetParentPath(ParentPath)))
	{
		if (ParentPath.IsEmpty())
		{
			if (_Root == NULL)
			{
				_Root = new CSevenZipArchiveItem();
			}

			Parent = _Root;
		}
		else
		{
			if (!_Map.Lookup(ParentPath, Parent))
			{
				Parent = new CSevenZipArchiveItem(_InArchive);
				_Map.SetAt(ParentPath, Parent);
			}
		}

		hr = S_OK;
	}

	return hr;
}